package com.example.flutter_plugin_test;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.MediaStore;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.flutter.Log;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugin.common.StringCodec;

/** Flutter插件测试插件 */
public class FlutterPluginTestPlugin implements FlutterPlugin, ActivityAware, MethodCallHandler, DefaultLifecycleObserver {
  /// 这个方法渠道在Flutter和原生Android之间通信
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// 当Flutter引擎脱离活动,此参考服务用于向 Flutter Engine 注册插件和注销插件

  ///事件通道
  private BasicMessageChannel basicMessageChannel;
  int status = 0;
  ///方法通道
  private MethodChannel methodChannel;

  String TAG = "Flutter";

  private MediaPlayer mediaPlayer;
  private Timer mTimer;
  private TimerTask mTimerTask;
  private int index = 0;
  private ArrayList<Bean> musics;
  private ArrayList<HashMap<String, Object>> musicList;
  private Bean bean;

  //isOpen 是否暂停
  private boolean isOpen =false;

  //定义活动
  private Activity activity;
  //定义Flutter插件绑定
  private FlutterPluginBinding activityBinding;

  @Override
  public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) {
    //实例化活动 = 活动插件绑定.获取活动()
    activity = activityPluginBinding.getActivity();
    //如果（活动 是 生命周期的主人）
    if (activity instanceof LifecycleOwner) {
      //实例化生命周期 = ((生命周期的主人) 活动).获取生命周期();
      Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
      getMusic();
      //生命周期.添加观察者
      lifecycle.addObserver(this);
    }
  }

  @Override
  public void onDetachedFromActivity() {
    //如果（活动 是 生命周期的主人）
    if (activity instanceof LifecycleOwner) {
      //实例化生命周期 = ((生命周期的主人) 活动).获取生命周期();
      Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
      //生命周期.删除观察者
      lifecycle.removeObserver(this);
    }
  }

  @Override
  public void onDetachedFromActivityForConfigChanges() {}

  @Override
  public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {}

  public void getMusic(){
    musicList = scanAllAudioFiles();
    musics = new ArrayList<Bean>();
    for(int i=0;i<musicList.size();i++){
      String musicFileUrl = musicList.get(i).get("musicFileUrl").toString();
      String musicTitle  = musicList.get(i).get("musicTitle").toString();
      String musicUrl = musicList.get(i).get("music_url").toString();
      String musicId = musicList.get(i).get("musicId").toString();
      String musicDuration = musicList.get(i).get("music_duration").toString();
      String musicFileName = musicList.get(i).get("music_file_name").toString();
      String musicAuthor = musicList.get(i).get("music_author").toString();
      Bean _bean = new Bean(musicFileUrl,musicTitle,musicUrl,musicId,musicDuration,musicFileName,musicAuthor);
      musics.add(_bean);
    }
    android.util.Log.d(TAG,"musics"+musics.size());
    if(musics.size()>0) {
      bean = musics.get(0);
    };
    android.util.Log.d(TAG,"bean.musicTitle"+bean.musicTitle);
    mediaPlayer = new MediaPlayer();
    mTimer = new Timer();
    mTimerTask = new TimerTask() {
      @Override
      public void run() {
        String time = timeParse(mediaPlayer.getCurrentPosition());
//        android.util.Log.e(TAG, " isOpen: "+isOpen+" 音乐运行的时间: "+time);
//        if(status == 1){
////          basicMessageChannel.send(map);
//        }

      }
    };
    mTimer.schedule(mTimerTask, 0, 100);
  }

  @Override
  ///连接到Flutter引擎(Flutter插件绑定 绑定)
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    activityBinding = flutterPluginBinding;
    //创建方法通道
    methodChannel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "methodChannel");
    //方法通道.回调
    methodChannel.setMethodCallHandler(this);
    //创建消息通道
    basicMessageChannel = new BasicMessageChannel(flutterPluginBinding.getBinaryMessenger(), "messageChanel", StandardMessageCodec.INSTANCE);
    basicMessageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler() {
      @Override
      public void onMessage(@Nullable Object message, @NonNull BasicMessageChannel.Reply reply) {

      }
    });
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("position", 21);
    map.put("duration", 100);
    basicMessageChannel.send(map);
  }


  @Override
  ///脱离Flutter引擎（Flutter插件绑定 绑定）
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    ///通道.设置方法调用处理程序(空)
    methodChannel.setMethodCallHandler(null);
    basicMessageChannel.setMessageHandler(null);
  }

  @Override
  //方法调用
  public void onMethodCall(@NonNull MethodCall methodCall, @NonNull Result result) {
    switch(methodCall.method){
      case "getPlatformVersion" :
        result.success("Android " + android.os.Build.VERSION.RELEASE);
        break;
      case "initMusics" :
        initMusics(result);
        break;
      case "playMusic" :
        index = (Integer) methodCall.argument("index");
        playMusic(musics.get(index).musicFileUrl);
        result.success("startMusic方法通道: 开始音乐");
        break;
      case "startMusic" :
        startMusic();
        result.success("startMusic方法通道: 开始音乐");
        break;
      case "stopMusic" :
        stopMusic();
        result.success("stopMusic方法通道: 暂停音乐");
        break;
      case "lastClick" :
        lastClick();
        result.success("lastClick方法通道: 上一首音乐");
        break;
      case "nextClick" :
        nextClick();
        result.success("nextClick方法通道: 下一首音乐");
        break;
      default :
        result.notImplemented();
    }

  }

  ///获取手机中的音乐列表信息
  public ArrayList<HashMap<String, Object>> scanAllAudioFiles(){
    //生成动态集合，用于存储数据
    ArrayList<HashMap<String, Object>> mylist = new ArrayList<HashMap<String, Object>>();
    ContentResolver localContentResolver = activityBinding.getApplicationContext().getContentResolver();
    //查询媒体数据库
    Cursor cursor = localContentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
    //遍历媒体数据库
    if(cursor.moveToFirst()){
      while (!cursor.isAfterLast()) {
        //歌曲编号
        int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
        //歌曲名
        String tilte = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
        //歌曲的专辑名：MediaStore.Audio.Media.ALBUM
        String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
        //歌曲的歌手名： MediaStore.Audio.Media.ARTIST
        String author = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
        //歌曲文件的路径 ：MediaStore.Audio.Media.DATA
        String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
        //歌曲的总播放时长 ：MediaStore.Audio.Media.DURATION
        int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
        //歌曲文件的大小 ：MediaStore.Audio.Media.SIZE
        Long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
        if(size>1024*800){//如果文件大小大于800K，将该文件信息存入到map集合中
          HashMap<String, Object> map = new HashMap<String, Object>();
          map.put("musicId", id);
          map.put("musicTitle", tilte);
          map.put("musicFileUrl", url);
          map.put("music_file_name", tilte);
          map.put("music_author",author);
          map.put("music_url",url);
          map.put("music_duration",duration);
          mylist.add(map);
        }
        cursor.moveToNext();
      }
    }
    android.util.Log.e(TAG, "本地音乐数组: musicList:" + mylist.size() );
    //返回存储数据的集合
    return mylist;
  }

  //时间转换
  public static String timeParse(long duration) {
    String time = "" ;
    long minute = duration / 60000 ;
    long seconds = duration % 60000 ;
    long second = Math.round((float)seconds/1000) ;
    if( minute < 10 ){
      time += "0" ;
    }
    time += minute+":" ;
    if( second < 10 ){
      time += "0" ;
    }
    time += second ;
    return time ;
  }

  void initMusics(@NonNull MethodChannel.Result result){
    ArrayList<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
    int i=0;
    Log.d("FLUTTER","初始化.音乐数量"+musics.size());
    for (Bean music : musics) {
      Map<String, Object> map = new HashMap<>();
      map.put("musicFileUrl",music.musicFileUrl);
      map.put("musicTitle",music.musicTitle);
      map.put("musicUrl",music.musicUrl);
      map.put("musicId",music.musicId);
      map.put("musicDuration",music.musicDuration);
      map.put("musicFileName",music.musicFileName);
      map.put("musicAuthor",music.musicAuthor);
      mapList.add(map);
      i++;
    }
    result.success(mapList);
  };

  //播放音乐
  public void playMusic(String path) {
    if(!isOpen){
      try {
        mediaPlayer.reset();
        mediaPlayer.setDataSource(path);
        mediaPlayer.prepare();
        mediaPlayer.start();
        isOpen = true;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }else{
      if(mediaPlayer.isPlaying()){
        mediaPlayer.pause();
      }else{
        mediaPlayer.start();
      }
      try {
        mediaPlayer.reset();
        mediaPlayer.setDataSource(path);
        mediaPlayer.prepare();
        mediaPlayer.start();
        isOpen = true;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  //开始或继续
  //暂停
  public void startMusic() {
    if(isOpen){
      mediaPlayer.pause();
      isOpen = false;
    }else{
      mediaPlayer.start();
      isOpen = true;
    }
  }

  //停止(结束)
  public void stopMusic() {
    if(mediaPlayer.isPlaying()){
      mediaPlayer.stop();
    }
  }

  //上一首
  public void lastClick() {
    if(mediaPlayer.isPlaying()){
      mediaPlayer.pause();
    }
    int i = index;
    if(i==0){
      i = musicList.size()-1;
    }else{
      i = i-1;
    }
    bean = musics.get(i);
    index = i;
    playMusic(bean.musicFileUrl);
  }

  //下一首
  public void nextClick() {
    if(mediaPlayer.isPlaying()){
      mediaPlayer.pause();
    }
    int i = index;
    if(i==musicList.size()-1){
      i = 0;
    }else{
      i = i+1;
    }
    bean = musics.get(i);
    index = i;
    playMusic(bean.musicFileUrl);
  }

}
